﻿using System;
using System.Collections.Generic;
using System.IO;
using Google.Protobuf;
using Net.Msg;

namespace Net.Public.Msg.Package
{
    /// <summary>
    /// 打包Protobuf消息的处理类
    /// </summary>
    public class TcpPackHandler : IPackage
    {
        public static IMessage TranslateMsgByMsgType(EMsgType msgType,byte[] body)
        {
            using MemoryStream ms = new MemoryStream(body);
            switch (msgType)
            {
                case  EMsgType.LoginMsg:
                    return LoginMsg.Parser.ParseFrom(ms);
                case EMsgType.TestMsg:
                    return TestMsg.Parser.ParseFrom(ms);
                case EMsgType.HeartMsg:
                    return HeartMsg.Parser.ParseFrom(ms);
                case EMsgType.ClientIdMsg:
                    return ClientIdMsg.Parser.ParseFrom(ms);
            }
            return default;
        } 
        /// <summary>
        /// 包含信息头
        /// </summary>
        /// <param name="msg"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public byte[] PackMsg<T>(T msg) where T : BaseMsg
        {
            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg), "Message cannot be null");
            }

            List<byte> byteList = new();
            //消息体
            var bodyBytes = msg.value.ToByteArray();
            //信息总长度 (信息头部4 + 实体（信息类型4字节 + 内容的全部字节）)
            msg.headLen = bodyBytes.Length + 4 + 4;
            var headBytes = BitConverter.GetBytes(msg.headLen);
            var msgTypeBytes = BitConverter.GetBytes((int)msg.msgType);
            foreach (var _ in headBytes)
            {
                byteList.Add(_);
            }
            foreach (var _ in msgTypeBytes)
            {
                byteList.Add(_);
            }
            foreach (var _ in bodyBytes)
            {
                byteList.Add(_);
            }

            return byteList.ToArray();
        }

        public T UnPackMsg<T>(byte[] msg) where T : BaseMsg, new()
        {
            
            using MemoryStream ms = new MemoryStream(msg);
            using BinaryReader reader = new BinaryReader(ms);
            // 读取头部信息（假设头部长度为4个字节）
            byte[] header = reader.ReadBytes(4);
            // 剩余部分作为消息体--> 包含信息类型和信息实体
            byte[] msgType = reader.ReadBytes(4);
            byte[] body = reader.ReadBytes((int)(ms.Length - ms.Position));
            using MemoryStream bSM = new MemoryStream(body);
            // 创建消息对象并填充属性
            T message = new T();
            message.headLen = BitConverter.ToInt32(header, 0);
            message.msgType = (EMsgType)BitConverter.ToInt32(msgType, 0);
            IMessage protoMsg = TranslateMsgByMsgType(message.msgType, body);
            message.value = protoMsg;
            return message;
        }
    }
}